//************************************************************************************************
// CONFIG
//************************************************************************************************
var jobsTemplateListName = "JobsAvailable";
//var website.get_url() = "sppss";

var jobsScheduledListName = "JobsScheduled";
//var website.get_url() = "sppss";

$(function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        sharePointReady();
    }, "sp.js");
});
function sharePointReady() {
    clientContext = SP.ClientContext.get_current();
    website = clientContext.get_web();
    clientContext.load(website);

    _userId = clientContext.get_web().get_currentUser();
    clientContext.load(_userId)
    //clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
};
//************************************************************************************************

//************************************************************************************************
// create the module and name it motivzApp
var motivzApp = angular.module('motivzApp', ['ngRoute']);

// configure our routes
motivzApp.config(function ($routeProvider) {
    $routeProvider

    // route for the home page
    .when('/', {
        templateUrl: 'views/home.html',
        controller: 'homeController'
    })

    // route for the create jobs page
    .when('/CREATE', {
        templateUrl: 'views/createJobs.html',
        controller: 'createJobsController'
    })

    // route for the view jobs page
    .when('/EDIT', {
        templateUrl: 'views/viewJobs.html',
        controller: 'viewJobsController'
    })

    // route back to the home page
    .otherwise({ redirectTo: '/' });
});

// create the controller and inject Angular's $scope
motivzApp.controller('homeController', function ($scope) {
    $scope.title = 'Home';
});

motivzApp.controller('createJobsController', function ($scope, $http) {
    $scope.title = 'Create Jobs';
    $http({
        method: 'GET',
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('JobsAvailable')/items",
        headers: { "Accept": "application/json;odata=verbose" }
    }).success(function (data, status, headers, config) {
        $scope.jobsAvailable = data.d.results;
        $scope.mySortFunction = function (item) {
            if (isNaN(item[$scope.sortExpression]))
                return item[$scope.sortExpression];
            return parseInt(item[$scope.sortExpression]);
        }
    }).error(function (data, status, headers, config) {
        // error handler?
    });

    $scope.MOTIVZviewDetails = function (job) {
        $("#MOTIVZjobFormContainer").html("");
        // BEGIN
        var jsonForm = JSON.stringify(job.jobTemplate);
        // http://jsonformatter.curiousconcept.com/
        var jobtitle = "Job Template: " + job.Title + " <i><small>(V: " + job.jobTemplateVersion + ")</small></i> for <b>" + job.jobPlatform + "</b>";
        var jobDescriptAuthorInfo = job.jobDescription + "<br><b>" + job.jobAuthor + "</b> <a href='" + job.jobAuthorURL + "' target='_blank'>" + job.jobAuthorURL + "</a>";

        var jsonHeader = JSON.stringify('{"ID" : "MOTIVZjobForm", "action" : "#", "method" : "get", "html":[{"type" : "b", "html" : "MOTIVZjobTitle"},{"type" : "div", "html" : "MOTIVZjobDesc"}');
        var jsonMOTIVZf = JSON.stringify('{"type" : "div","html" : "<hr>"},{"type" : "u", "html" : "MOTIVZ Requirements"},{"type" : "hidden", "name" : "MOTIVZ_SourceJobVersion", "value" : "' + job.jobTemplateVersion + '"},{"type" : "hidden", "name" : "MOTIVZ_jobTemplate", "value" : "' + job.Title + '"},{"type" : "text", "id" : "MOTIVZ_Title", "name" : "MOTIVZ_Title", "caption" : "Displayed Job Name", "value" : ""},{"type" : "select", "id" : "MOTIVZ_Frequency", "name" : "MOTIVZ_Frequency", "caption" : "Job Frequency", "options" : {"Minute" : "Minute", "Hourly" : "Hourly", "Daily" : "Daily", "Weekly" : "Weekly", "Monthly" : "Monthly"}},{"type" : "select", "id" : "MOTIVZ_FreqInterval", "name" : "MOTIVZ_FreqInterval", "caption" : "Frequency Interval", "options" : {"1" : "1", "2" : "2", "5" : "5", "15" : "15", "30" : "30", "90" : "90"}}, {"type" : "checkboxes", "id" : "MOTIVZ_FrequencyDay", "name" : "MOTIVZ_FrequencyDay", "caption" : "Frequency Days", "options" : {"Monday" : "Monday", "Tuesday" : "Tuesday", "Wednesday" : "Wednesday", "Thursday" : "Thursday", "Friday" : "Friday", "Saturday" : "Saturday", "Sunday" : "Sunday"}},{"type" : "select", "id" : "MOTIVZ_Active", "name" : "MOTIVZ_Active", "caption" : "Active?", "options" : {"1" : "YES", "0" : "NO"}},{"type" : "div","html" : "<hr>"},{"type" : "u", "html" : "Job Specific Requirements"}');
        var jsonFooter = JSON.stringify('{"type" : "submit", "id" : "MOTIVZcreateJob", "value" : "Create"}]}');

        jsonHeader = jsonHeader.replace("MOTIVZjobTitle", "").replace("MOTIVZjobDesc", "");
        $("#MOTIVZjobTitle").html(jobtitle);
        $("#MOTIVZjobDescription").html(jobDescriptAuthorInfo);

        var fullJson = ((jsonHeader + jsonMOTIVZf + jsonForm + jsonFooter).replace(/}""{/g, '},{').replace(/\\n/g, '').replace(/\\/g, '')).toString();
        fullJson = fullJson.substring(0, fullJson.length - 1).replace('"', '');
        fullJson = JSON.parse(fullJson);

        $("#MOTIVZjobFormContainer").dform(fullJson, function (data) {
            this //-> Generated $('#myform')
            data //-> data from path/to/form.json
        });
        // Now that the form is built...
        // 1
        // Add event handler to submit button
        var MOTIVZsubmit = document.getElementById("MOTIVZcreateJob");
        // ADD class
        MOTIVZsubmit.setAttribute("class", "btn btn-success");
        // Add event
        MOTIVZsubmit.addEventListener("click", MOTIVZcreateJob, false);
        // 2
        // Add a create button that will show the actual form fields
        $("#MOTIVZjobFieldsShow").html('<a class="btn btn-primary" id="MOTIVZshowFormFields">Schedule an instance of this</a>');
        // Add event handler to submit button
        var MOTIVZshowJobFields = document.getElementById("MOTIVZjobFieldsShow");
        // Add event
        MOTIVZshowJobFields.addEventListener("click", MOTIVZshowJobFieldsClick, false);

        // 3
        // Hide the form portion of the modal initially
        $("#MOTIVZjobForm").hide();
        $("#MOTIVZjobFieldsShow").show();
        // END
        $("#MOTIVZscheduleJobForm").modal('show');
    };
    function MOTIVZshowJobFieldsClick() {
        $("#MOTIVZjobForm").show();
        $("#MOTIVZjobFieldsShow").hide();
    };
    function MOTIVZcreateJob(e) {
        e.preventDefault();
        // Show modal
        $("#MOTIVZcreatingJobmodal").modal('toggle');

        //var dataSerial = $("#MOTIVZjobForm :input").serializeArray();
        var dataSerial = $("#MOTIVZjobForm").serializeArray();
        // Now get the checkbox values

        var checkboxValues = [];

        /* Because serializeArray() seems to ignore set checkboxes and radio buttons: */
        $(".ui-dform-checkbox:checked").each(function () {
            checkboxValues.push({ name: this.name, value: this.value });
        });

        addListItem(jobsScheduledListName, dataSerial, checkboxValues, MOTIVZjobCreateSuccess, MOTIVZjobCreateFailure);
        /*
        http://msurguy.github.io/ladda-bootstrap/
        https://github.com/msurguy/ladda-bootstrap
       
         var l = Ladda.create(this);
         l.start();
         $.post("your-url",
             { data : data },
           function(response){
             console.log(response);
           }, "json")
         .always(function() { l.stop(); });
         return false;
		//});
		*/
    };
});

motivzApp.controller('viewJobsController', function ($scope, $http) {
    // Displayed page title
    $scope.title = 'View/Edit Jobs';
    // Get the list data
    $http({
        method: 'GET',
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('jobsScheduled')/items",
        headers: { "Accept": "application/json;odata=verbose" }
    }).success(function (data, status, headers, config) {
        // Returned list data
        $scope.jobsScheduled = data.d.results;
        // Search/filter data on page
        $scope.mySortFunction = function (item) {
            if (isNaN(item[$scope.sortExpression]))
                return item[$scope.sortExpression];
            return parseInt(item[$scope.sortExpression]);
        }
    }).error(function (data, status, headers, config) {
        // error handler?
    });
}).directive('jobElement', function () {
    // Format data on page
    return {
        // http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters
        controller: function($scope){
            $scope.MOTIVZpleaseWaitAs = function (jobTitle, jobID, jobAction, jobValue) {
                // RESET
                    // Stop the icon from spinning if it has the class previously applied.
                    $("#modalIcon").removeClass("fa-spin").removeClass("fa-smile-o makeGreen").removeClass("fa-frown-o makeRed").addClass("fa-cog");
                    // Remove any messages from the error div
                    $("#ChangeJobvalueError").html("");
                    // Reset the cancel button text
                    $("#MOTIVZcloseModal").html("Cancel");

                // ACTION
                    // Enable the submit button
                    $("#MOTIVZupdateJob").removeAttr("disabled").html("Apply");
                    // Update the button actions
                    // Add event handler to submit button
                    var MOTIVZsubmit = document.getElementById("MOTIVZupdateJob");
                    // ADD class and function to button
                    if (jobAction === "DELETE") {
                        MOTIVZsubmit.setAttribute("class", "btn btn-danger");
                        $("#modalIcon").removeClass("fa-cog").addClass("fa-exclamation-triangle");
                        $("#MOTIVZupdateJob").html("Delete");
                        // Add event handler to submit button
                        MOTIVZsubmit.addEventListener("click", MOTIVZdeleteJob, false);
                    } else {
                        MOTIVZsubmit.setAttribute("class", "btn btn-warning");
                        // Add event handler to submit button
                        MOTIVZsubmit.addEventListener("click", MOTIVZupdateJob, false);
                    };

                // INFO
                    // Add the job specific text
                    $("#ChangeJobvalueTitle").html("").html("<b>JOB: " + jobTitle + "</b>");
                    $("#ChangeJobvalueJobID").html("").text(jobID);
                    $("#ChangeJobvalueAction").html("").html(jobAction);
                    $("#ChangeJobvalueValue").html("").html(jobValue);
            };
        },
        scope: {
            job: '=jobElement'
        },
        restrict: 'EA',
        template:  '<td>{{job.Title}}</td> \
                    <td> \
                        <!-- {{job.ActiveStatus}} -->\
                        <a ng-show="job.ActiveStatus === \'Yes\'" ng-click="MOTIVZpleaseWaitAs(job.Title,job.ID,\'ActiveStatus\',\'No\')" class="btn btn-default" data-toggle="modal" data-target="#modal1" data-id="{{job.ID}}"><i class="fa fa-power-off makeGreen" aria-hidden="true"></i></a> \
                        <a ng-show="job.ActiveStatus === \'No\'" ng-click="MOTIVZpleaseWaitAs(job.Title,job.ID,\'ActiveStatus\',\'Yes\')" class="btn btn-default" data-toggle="modal" data-target="#modal1" data-id="{{job.ID}}"><i class="fa fa-power-off makeRed" aria-hidden="true"></i></a> \
                    </td> \
                    <!-- <td>:: {{job.FrequencyDay.results}}</td> -->\
                    <td> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Sunday\') > -1 ? \'label label-success\' : \'label label-danger\'">Sun</span> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Monday\') > -1 ? \'label label-success\' : \'label label-danger\'">Mon</span> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Tuesday\') > -1 ? \'label label-success\' : \'label label-danger\'">Tue</span> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Wednesday\') > -1 ? \'label label-success\' : \'label label-danger\'">Wed</span> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Thursday\') > -1 ? \'label label-success\' : \'label label-danger\'">Thu</span> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Friday\') > -1 ? \'label label-success\' : \'label label-danger\'">Fri</span> \
                        <span ng-class="job.FrequencyDay.results.indexOf(\'Saturday\') > -1 ? \'label label-success\' : \'label label-danger\'">Sat</span> \
                    </td> \
                    <td> \
                        <a ng-click="MOTIVZviewDetails(job)" class="btn btn-primary announce" data-toggle="modal" data-id="{{job.ID}}"><i class="fa fa-database" aria-hidden="true"></i></a> \
                        <a ng-click="MOTIVZviewDetails(job)" class="btn btn-primary announce" data-toggle="modal" data-id="{{job.ID}}"><i class="fa fa-play-circle-o" aria-hidden="true"></i></a> \
                        <a ng-click="MOTIVZviewDetails(job)" class="btn btn-primary announce" data-toggle="modal" data-id="{{job.ID}}"><i class="fa fa-edit" aria-hidden="true"></i></a> \
                        <a ng-click="MOTIVZviewDetails(job)" class="btn btn-primary announce" data-toggle="modal" data-id="{{job.ID}}"><i class="fa fa-copy" aria-hidden="true"></i></a> \
                    </td> \
                    <td> \
                        <a ng-click="MOTIVZpleaseWaitAs(job.Title,job.ID,\'DELETE\',\'YES\')" class="btn btn-primary announce"  data-toggle="modal" data-target="#modal1" data-id="{{job.ID}}"><i class="fa fa-trash" aria-hidden="true"></i></a> \
                    </td>',
    };
});

//######################################################################################
// BEGIN: 
//######################################################################################
    function MOTIVZjobCreateSuccess(data) { 
        console.log("Completed successfully.");
        $("#MOTIVZcreatingJobmodal").modal('toggle');
    }
//######################################################################################
// END: 
//######################################################################################
    function GetItemTypeForListName(name) {
        return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
    }
//######################################################################################
// BEGIN: 
//######################################################################################
    function MOTIVZjobCreateFailure(data) {
        console.log("Operation failed." + JSON.stringify(data));
    }
//######################################################################################
// END: 
//######################################################################################

//######################################################################################
// BEGIN: GET a list item
//######################################################################################
    // READ SPECIFIC ITEM operation
    // itemId: The id of the item to get
    // listName: The name of the list you want to get items from
    // siteurl: The url of the site that the list is in. 
    // success: The function to execute if the call is sucesfull
    // failure: The function to execute if the call fails
    function getListItemWithId(jobItemID, success, failure) {
        var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + jobsScheduledListName + "')/items?$filter=Id eq " + jobItemID;
        $.ajax({
            url: url,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                if (data.d.results.length == 1) {
                    success(data.d.results[0]);
                }
                else {
                    failure("Multiple results obtained for the specified Id value");
                }
            },
            error: function (data) {
                failure(data);
            }
        });
    }
//######################################################################################
// END: GET a list item
//######################################################################################

//######################################################################################
// BEGIN: Delete a 'JobsScheduled' list item
//######################################################################################
    // occurs when a user clicks the delete button
    function MOTIVZdeleteJob() {
        var jobItemID = $("#ChangeJobvalueJobID").text();
        $("#modalIcon").removeClass("fa-exclamation-triangle").addClass("fa-cog").addClass("fa-cog").addClass("fa-spin");
        var url = _spPageContextInfo.webAbsoluteUrl;

        deleteListItem(jobItemID, function () {
            $("#ChangeJobvalueError").html("Item deleted successfully:  - page reloading...");
            // This needs to be an Angular $state reload...
            window.location.reload();
        }, function () {
            $("#ChangeJobvalueError").html("An error occured. Please try again:  - page reloading...");
            // This needs to be an Angular $state reload...
            window.location.reload();
        });
    }

    // Delete Operation
    // itemId: the id of the item to delete
    // listName: The name of the list you want to delete the item from
    // siteurl: The url of the site that the list is in. 
    // success: The function to execute if the call is sucesfull
    // failure: The function to execute if the call fails
    function deleteListItem(jobItemID, success, failure) {
        getListItemWithId(jobItemID, function (data) {
            $.ajax({
                url: data.__metadata.uri,
                type: "POST",
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-Http-Method": "DELETE",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "If-Match": data.__metadata.etag
                },
                success: function (data) {
                    console.log(data);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        },
       function (data) {
           failure(data);
       });
    }
//######################################################################################
// END: Delete a 'JobsScheduled' list item
//######################################################################################

//######################################################################################
// BEGIN: Update a field in a JobsScheduled list item
//######################################################################################
    function MOTIVZupdateJob() {
        // Spin the icon
        $("#modalIcon").addClass("fa-spin");
        // Hide the button
        $("#MOTIVZupdateJob").prop("disabled", true).html("Applying");
        // Get the values
        var jobItemID = $("#ChangeJobvalueJobID").text();
        var jobItemSetting = $("#ChangeJobvalueAction").text();
        var jobItemValue = $("#ChangeJobvalueValue").text();

        // Update the item
        var itemProperties = JSON.parse('{"' + jobItemSetting + '":"' + jobItemValue + '"}');
        updateListItem(_spPageContextInfo.webAbsoluteUrl, jobsScheduledListName, jobItemID, itemProperties, printInfo, logError);
        function printInfo() {
            $("#MOTIVZupdateJob").html("Success");
            $("#MOTIVZcloseModal").html("Close").addClass("btn btn-success");
            $("#modalIcon").removeClass("fa-spin").removeClass("fa-cog").addClass("fa-smile-o makeGreen");

            $("#ChangeJobvalueError").html('Item has been updated - page reloading...');
            // This needs to be an Angular $state reload...
            window.location.reload();
        }
        function logError(error) {
            $("#MOTIVZupdateJob").addClass("btn-danger").html("Error");
            $("#MOTIVZcloseModal").html("Close");
            $("#modalIcon").removeClass("fa-spin").removeClass("fa-cog").addClass("fa-frown-o makeRed");
            $("#ChangeJobvalueError").html(JSON.stringify(error));
        }
    };
    function updateJson(endpointUri, payload, success, error) {
        $.ajax({
            url: endpointUri,
            type: "POST",
            data: JSON.stringify(payload),
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": "*"
            },
            success: success,
            error: error
        });
    }

    function getItemTypeForListName(name) {
        return "SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    }

    function updateListItem(webUrl, listTitle, listItemId, itemProperties, success, failure) {
        console.log(webUrl + " : " + listTitle + " : " + listItemId + " : " + itemProperties);
        var listItemUri = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + listItemId + ")";
        var itemPayload = {
            '__metadata': { 'type': getItemTypeForListName(listTitle) }
        };
        for (var prop in itemProperties) {
            itemPayload[prop] = itemProperties[prop];
        }
        updateJson(listItemUri, itemPayload, success, failure);
    }
//######################################################################################
// END: Update a field in a JobsScheduled list item
//######################################################################################

//######################################################################################
// BEGIN: Create list item
//######################################################################################
function addListItem(jobsScheduledListName, dataSerial, checkboxValues, MOTIVZjobCreateSuccess, MOTIVZjobCreateFailure) {

    // Hide the form modal
    $("#MOTIVZscheduleJobForm").modal('hide');
    // Show the creating modal
    $("#MOTIVZcreatingJobmodal").modal('show');

    var packageValues = "";

    jQuery.each(dataSerial, function (i, field) {
        //console.log("'"+field.name + "' = '" + field.value + "'..." );
        var thisField = field.name;
        if (thisField.indexOf("MOTIVZ_") >= 0) {
            // ignore
        } else {
            // This is a packagae specific field/value. 
            packageValues += '{"' + field.name + '" : "' + field.value + '"},';
        }
    });
    // Remove last comma
    packageValues = packageValues.substring(0, packageValues.length - 1);
    // Make it look like JSON
    packageValues = "{" + packageValues + "}";
    console.log(packageValues);

    // Checkbox values
    var FrequencyDay = [];
    jQuery.each(checkboxValues, function (i, field) {
        FrequencyDay.push(field.value);
    });
    // Complete the string
    // {'results' : [FrequencyDay]}
    //FrequencyDayStr = "{'results' : ["+FrequencyDay+"]}";
    //FrequencyDayStr = JSON.parse(FrequencyDayStr);
    console.log(FrequencyDay);

    var len = dataSerial.length;
    dataObj = {};
    for (i = 0; i < len; i++) {
        dataObj[dataSerial[i].name] = dataSerial[i].value;
    }

    // Use the ID to update page to show that the record has been added
    //var jobID = dataObj.ID;
    //console.log("jobID = " + jobID);
    //$(".open-MOTIVZscheduleJobForm[data-id='" + jobID + "']").html('<button class="btn btn-primary" type="button">Job added</button>');

    var jobTitle = dataObj.MOTIVZ_Title;
    var jobActive = dataObj.MOTIVZ_Active;
    if (jobActive == 1) {
        jobActive = "Yes";
    } else if (jobActive == 0) {
        jobActive = "No";
    }

    var jobFrequency = dataObj.MOTIVZ_Frequency;
    var jobFreqInterval = dataObj.MOTIVZ_FreqInterval;
    var jobTemplateVersion = dataObj.MOTIVZ_SourceJobVersion;
    var jobSourceJob = dataObj.MOTIVZ_jobTemplate;
    var jobJSONValue = packageValues;
    console.log(jobTitle + " - " + jobActive + " - " + jobFrequency + " - " + jobFreqInterval + " - " + jobTemplateVersion + " - " + jobSourceJob + " - " + jobJSONValue);

    var itemType = GetItemTypeForListName(jobsScheduledListName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": jobTitle,
        "ActiveStatus": jobActive,
        "Frequency": jobFrequency,
        "FreqInterval": jobFreqInterval,
        "FrequencyDay": { 'results': FrequencyDay },
        "TemplateVersion": jobTemplateVersion,
        "SourceJob": jobSourceJob,
        "JSONValue": jobJSONValue
    };

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + jobsScheduledListName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            MOTIVZjobCreateSuccess(data);
        },
        error: function (data) {
            MOTIVZjobCreateFailure(data);
        }
    });
}
//######################################################################################
// END: Create list item
//######################################################################################
